#include "stdafx.h"

#include "GameApp.h"
#include "mmsystem.h"

//Fucking Global Variables 


LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

GameApp::GameApp()
:hInstance(NULL)
{
	this;
	mWidth = 800;
	mHeight = 600;
}

GameApp::~GameApp()
{
}

ATOM GameApp::MyRegisterClass(const char* wndName, HINSTANCE hInst)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInst;
	wcex.hIcon			= NULL;
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;
	char* clsName = new char[256];
	memset(clsName, 0, 256);
	::sprintf_s(clsName, 256, "%s Window", wndName);
	wcex.lpszClassName	= clsName;
	wcex.hIconSm		= NULL;

	int ret = RegisterClassEx(&wcex);
	return ret;
}

void GameApp::InitInstance(const char* wndName, HINSTANCE hInst)
{
	RECT rect;
	rect.left = 300;
	rect.top  = 100;
	rect.right = 800 + 300;
	rect.bottom = 600 + 100;

	::AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, TRUE);

	char clsName[256] = {0};
	::sprintf_s(clsName, 256, "%s Window", wndName);
	mHwnd = ::CreateWindow(clsName, wndName, WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL);

	int err = ::GetLastError();

	::MoveWindow(mHwnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);

	::ShowWindow(mHwnd, SW_SHOW);
	::UpdateWindow(mHwnd);
}

void GameApp::SetupWindow(const char* wndName, int width, int height, HINSTANCE hInst)
{
	mWidth = width;
	mHeight = height;
	mIsWindowed = true;

	MyRegisterClass(wndName, hInst);
	InitInstance(wndName, hInst);
}

void GameApp::SetupScene()
{

}

void GameApp::PerFrame( double deltaTime )
{
}

DWORD GameApp::Go()
{
	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	double lastTime = timeGetTime();

	while (msg.message != WM_QUIT) 
	{
		if (::PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			double currTime = timeGetTime();
			double deltaTime = (currTime - lastTime) * 0.001f;

			if(deltaTime > 0.05f)
				deltaTime = 0.05f;

			if(deltaTime > 0.03f)
			{
				PerFrame(deltaTime);
				lastTime = currTime;
			}
			else
				Sleep(5);
		}
	}

	return msg.wParam;
}

int APIENTRY WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR     lpCmdLine,
	int       nCmdShow)
{
	GameApp *pApp = GetApplication();
	pApp->SetupWindow("Maze", 800, 600, hInstance);
	pApp->SetupScene();

	DWORD msg = 0;
	msg = pApp->Go();
}